﻿using System.IO;
using System.Windows;
using System.Windows.Threading;
using System.Windows.Forms;
using System.Windows.Media;
using MessageBox = System.Windows.MessageBox;

namespace Calc_Map_NO
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private string folderPath;
        private int totalFiles = 0;
        private int processedFiles = 0;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void SelectFolderButton_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new FolderBrowserDialog();

            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                folderPath = dialog.SelectedPath;
                FolderPathTextBox.Text = folderPath;
                UpdateStatus("已选择文件夹: " + folderPath);
            }

        }

        private async void ProcessButton_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(folderPath))
            {
                UpdateStatus("开始处理...");
                //UpdateProgress();
                await BatchProcessCSVAsync(folderPath);
            }
            else
            {
                MessageBox.Show("请先选择文件夹！", "请选择文件夹", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 计算图幅号
        /// </summary>
        /// <param name="e">东坐标</param>
        /// <param name="n">北坐标</param>
        /// <returns></returns>
        private string CalcMapNo(double e, double n)
        {
            // 计算图幅的左下角东、北坐标
            var eBase = (int)(Math.Floor(e / 2500) * 2500);
            var nBase = (int)(Math.Floor(n / 2000) * 2000);

            // 取4位左下角图幅号，不够补零
            var eBaseStr = eBase.ToString()[..4];
            var nBaseStr = nBase.ToString()[..4];

            // 计算在2500*2000图幅内的相对坐标
            var eInBig = e - eBase;
            var nInBig = n - nBase;

            // 计算在2500*2000图幅内的行列号，row-行；col-列
            var midCol = (int)Math.Ceiling(eInBig / 500);
            var midRow = (int)Math.Ceiling(nInBig / 400);
            var midNo = 5 * (midRow - 1) + midCol;

            // 计算在中矩形的相对坐标
            var eInMid = eInBig % 500;
            var nInMid = nInBig % 400;

            // 判断小矩形的罗马数字   Ⅰ Ⅱ Ⅲ Ⅳ
            var isNorth = nInMid >= 200;
            var isEast = eInMid >= 250;

            //var roman = isNorth switch
            //{
            //    true when isEast => "Ⅱ",
            //    true => "Ⅰ",
            //    _ when isEast => "Ⅳ",
            //    _ => "Ⅲ"
            //};

            var roman = (nInMid >= 200, eInMid >= 250) switch
            {
                (true, false) => "Ⅰ",
                (true, true) => "Ⅱ",
                (false, false) => "Ⅲ",
                (false, true) => "Ⅳ",

            };


            // 组合图幅号
            return $"{eBaseStr}-{nBaseStr}-{midNo}-{roman}";
        }

        private async Task ProcessCSVAsync(string inputFile)
        {
            // 确定输出文件名（在源文件后追加“_with_mapno”）
            var fileDir = Path.GetDirectoryName(inputFile);
            var baseName = Path.GetFileNameWithoutExtension(inputFile);
            var ext = Path.GetExtension(inputFile);
            var outputFile = Path.Combine(fileDir, $"{baseName}_with_mapno{ext}");

            var allLines = new List<string[]>();

            try
            {
                using var reader = new StreamReader(inputFile);
                //string line;
                bool isHeader = true;
                while (await reader.ReadLineAsync() is { } line)
                {
                    var values = line.Split(',');
                    if (isHeader)
                    {
                        //allLines.Add(values.Concat(["图幅号"]).ToArray());
                        allLines.Add([.. values, "图幅号"]);
                        isHeader = false;
                    }
                    else
                    {
                        try
                        {
                            var north = double.Parse(values[1]);
                            var east = double.Parse(values[2]);

                            // 计算图幅号
                            var mapNo = CalcMapNo(east, north);
                            // 写入新行（原始数据+图幅号）
                            //allLines.Add(values.Concat([mapNo]).ToArray());
                            allLines.Add([.. values, mapNo]);
                        }
                        catch (Exception e)
                        {
                            // 处理数据转换错误或者列数不足的情况
                            UpdateStatus($"处理{string.Join(",", values)}行时出错：{e.Message}");
                            // 保留原始行，图幅号标记为错误
                            //allLines.Add(values.Concat(["ERROR"]).ToArray());
                            allLines.Add([.. values, "ERROR"]);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                UpdateStatus($"读取文件 {inputFile} 时出错：{ex.Message}", true);
                return;
            }

            try
            {
                using var writer = new StreamWriter(outputFile, false, System.Text.Encoding.UTF8);
                foreach (var line in allLines)
                    writer.WriteLine(string.Join(",", line));
            }
            catch (Exception ex)
            {
                UpdateStatus($"写入文件 {outputFile} 时出错：{ex.Message}", true);
                return;
            }

            UpdateStatus($"处理完成，结果已保存到：{outputFile}");
            UpdateProgress(++processedFiles, totalFiles);
        }


        private async Task BatchProcessCSVAsync(string inputDir)
        {
            if (!Directory.Exists(inputDir))
            {
                MessageBox.Show($"❌错误：文件夹{inputDir}不存在");
                return;
            }

            // 获取文件夹下所有CSV文件
            string[] csvFiles = Directory.GetFiles(inputDir, "*.csv", SearchOption.TopDirectoryOnly);

            if (csvFiles.Length == 0)
            {
                MessageBox.Show($"在{inputDir}中没有找到csv文件");
                return;
            }

            totalFiles = csvFiles.Length;
            processedFiles = 0;
            UpdateStatus($"共找到{totalFiles}个CSV文件，开始处理...");
            UpdateProgress(processedFiles, totalFiles);

            // 处理每个CSV文件
            var tasks = new List<Task>();
            foreach (var csvFile in csvFiles)
            {
                tasks.Add(ProcessCSVAsync(csvFile));
            }
            await Task.WhenAll(tasks);
            UpdateStatus($"✓批量处理完成！共处理{csvFiles.Length}个文件。");
        }

        // 更新状态栏消息
        private void UpdateStatus(string message, bool isError = false)
        {
            Dispatcher.Invoke(() =>
            {
                StatusTextBlock.Text = message;
                StatusTextBlock.Foreground = isError ? System.Windows.Media.Brushes.Red : System.Windows.Media.Brushes.Black;
            });
        }

        // 更新处理进度
        private void UpdateProgress(int processed, int total)
        {
            Dispatcher.Invoke(() =>
            {
                processedFiles = processed;
                totalFiles = total;
                ProgressTextBlock.Text = $"{processed}/{total}";
            });
        }
    }

}